<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="商品编码" prop="cinvcode">
        <el-input
          v-model="queryParams.cinvcode"
          placeholder="请输入"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="cinvname">
        <el-input
          v-model="queryParams.cinvname"
          placeholder="请输入"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规格型号" prop="cinvstd">
        <el-input
          v-model="queryParams.cinvstd"
          placeholder="请输入"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
      <el-form-item style="float: right;">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
          v-show="isAddRow"
        >增行</el-button>
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="commitOrder"
          v-show="isAddRow"
        >提交订单</el-button>

      </el-form-item>
    </el-form>


    <el-table
      v-loading="loading"
      :data="cardetailList"
      @selection-change="handleSelectionChange"
      show-summary
      :summary-method="getSummaries"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="NO" align="center" type="index" :index="indexMethod" />
      <el-table-column label="客户编码" align="center" prop="mainid.userId.cust.ccuscode"/>
      <el-table-column label="客户名称" align="center" prop="mainid.userId.cust.ccusname"/>
      <el-table-column label="下达单" align="center" prop="mainid.userId.userName"/>

      <el-table-column label="产品编码" align="center" prop="cinvcode">
       <template #default="scope">
          <div style="position: relative; display: flex; align-items: flex-end;">
            <el-input  v-model="scope.row.cinvcode"   size="small"   style="width: 120px;"  readonly/>
            <el-button     icon="el-icon-search"  size="small"      style="position: absolute; right: 0; bottom: 0; padding: 2px 4px;"
              @click="openProductDialog(scope.row)"
              :aria-label="'Search product for ' + scope.row.cinvcode"
              title="Search product"
            ></el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="产品名称" align="center" prop="cinvname" />
      <el-table-column label="规格型号" align="center" prop="cinvstd" />
      <el-table-column label="单位" align="center" prop="comunitname" />
      <el-table-column label="标准价格" align="center" prop="saleprice" />
      <el-table-column label="折扣率" align="center" prop="rate" />
      <el-table-column label="单价" align="center" prop="price" />
      <el-table-column label="税率" align="center" prop="itaxrate" />
      <el-table-column label="库存数量" align="center" prop="num" />
      <el-table-column label="订购数量" align="center" width="180"   class-name="col-order"  prop="orderNum" >
      <template #default="scope">
        <div class="order-action-row">
          <el-button
            size="small"
            class="order-btn"
            @click="decrease(scope.row, scope.$index)"
            :disabled="scope.row.orderNum <= 0"
            icon="el-icon-minus"
          ></el-button>
          <el-input-number
            v-model="scope.row.orderNum"
            :min="0"
            :step="1"
            :controls="false"
            style="width:40px;margin-right:0px;"
            @change="handleOrderNumChange(scope.row, scope.$index)"
          />
          <el-button
            size="small"
            class="order-btn"
            @click="increase(scope.row,scope.$index)"
            :disabled="scope.row.orderNum >= scope.row.num"
            icon="el-icon-plus"
          ></el-button>
        </div>
      </template>
      </el-table-column>
      <el-table-column label="无税金额" align="center" prop="money" >
      <template #default="scope">
          <div>
           {{ parseFloat(scope.row.money).toFixed(2)}}
          </div>
      </template>
      </el-table-column>
      <el-table-column label="税额" align="center" prop="tax" >
      <template #default="scope">
          <div>
           {{ parseFloat(scope.row.tax).toFixed(2)}}
          </div>
      </template>
      </el-table-column>

      <el-table-column label="价税合计" align="center" prop="amount" >
      <template #default="scope">
          <div>
           {{ parseFloat(scope.row.amount).toFixed(2)}}
          </div>
      </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="small"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:cardetail:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog      title="选择商品"      :visible.sync="productDialogVisible"     width="98%" >
      <Inventory    @rowDbclick="onProductSelect"    :isShowcar=false  />
    </el-dialog>


  </div>
</template>

<script>
import { listCardetail, getCardetail, delCardetail, addCardetail, updateCardetail, exportCardetail } from "@/api/business/cardetail";
import   Inventory   from  '@/views/business/Inventory/index.vue';
import {saveCar} from "@/api/business/Inventory";



export default {
  name: "Cardetail",
  components: {
    Inventory
  },
  props:{
    isAddRow:{
      type:Boolean,
      default:true,
    }

  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      // 总条数
      total: 0,
      irowno:0,
      // cardetail表格数据
      cardetailList: [],
      // 弹出层标题
      title: "",
      // 字典
      idOptions: [],
      // 字典
      cinvcodeOptions: [],
      // 字典
      mainidOptions: [],
      // 字典
      ordernumOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 1000,
        cinvcode: null,
        mainid: null,
        ordernum: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      productDialogVisible: false,
      productSelectRow: null,
      selectedRows: [],
    };
  },
  created() {
    this.getList();
    this.getDicts("${column.dictType}").then(response => {
      this.idOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.cinvcodeOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.mainidOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.ordernumOptions = response.data;
    });
  },
  methods: {
    /** 查询cardetail列表 */
    getList() {
      this.loading = true;
      listCardetail(this.queryParams).then(response => {
        this.cardetailList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.irowno=this.cardetailList.map(item=>item.irowno).reduce((a,b)=>Math.max(a,b),0);
      });

    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        cinvcode: null,
        mainid: null,
        ordernum: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectedRows = selection;
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.cardetailList.push({
        id: null,
        cinvcode: '',
        cinvname: '',
        cinvstd: '',
        comunitname: '',
        saleprice: 0,
        rate: 0,
        price: 0,
        itaxrate: 13,
        num: 0,
        orderNum: 0,
        money: 0,
        tax: 0,
        amount: 0,
        irowno: ++this.irowno,
      });
    },commitOrder() {
      // 获取选中的行记录
      const selected = this.selectedRows;
      console.log('选中的行：', selected);
      if (selected.length === 0) {
        this.msgWarning("请至少选择一行商品进行下单");
        return;
      }

      // 你可以在这里提交订单或做其它操作
      debugger;
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCardetail(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.getList();
            });
          } else {
            addCardetail(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = parseInt(row.id);
      if (isNaN(id) || id === undefined) {
        // 本地新增行，直接从数组中删除
        const idx = this.cardetailList.indexOf(row);
        if (idx > -1) this.cardetailList.splice(idx, 1);
        return;
      }
      this.$confirm('是否确认删除购物车中编码为"' + row.cinvcode + '"的商品吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delCardetail(id);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },

    indexMethod(index) {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
    },
       handleOrderNumChange(row,idx) {
      const price = parseFloat(row.price) || 0;
      const num = parseFloat(row.orderNum) || 0;
      row.amount = (price * num).toFixed(2); // 价税合计保留两位小数
      row.money= parseFloat(parseFloat(row.amount)/(parseFloat(row.itaxrate)+100)*100).toFixed(2);
      row.tax=row.amount-row.money;
      debugger;
      this.cardetailList[idx]=row;
      saveCar(this.cardetailList);
      },
    increase(row,idx) {
      if (row.orderNum < row.num) {
        row.orderNum++;
        this.handleOrderNumChange(row,idx);
      }
    },
    decrease(row,idx) {
      if (row.orderNum > 0) {
        row.orderNum--;
        this.handleOrderNumChange(row,idx);
      }
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 1) { // NO列
          sums[index] = '合计';
          return;
        }
        if ([
          'num',      // 库存数量
          'orderNum', // 订购数量
          'money',    // 无税金额
          'tax',      // 税额
          'amount'    // 价税合计
        ].includes(column.property)) {
          const values = data.map(item => {
            const val = Number(item[column.property]);
            return isNaN(val) ? 0 : val;
          });
          let sum = values.reduce((prev, curr) => prev + curr, 0);
          // 金额类保留两位小数
          if (['money', 'tax', 'amount'].includes(column.property)) {
            sum = sum.toFixed(2);
          }
          sums[index] = sum;
        } else {
          sums[index] = '';
        }
      });
      return sums;
    },
    openProductDialog(row) {
      debugger;
      this.productSelectRow = row;
      this.productDialogVisible = true;
    },

    onProductSelect(product) {
      if (this.productSelectRow) {
        this.productSelectRow.cinvcode = product.cinvcode;
        this.productSelectRow.cinvname = product.cinvname;
        this.productSelectRow.cinvstd = product.cinvstd;
        this.productSelectRow.comunitname=product.comunitname;
        this.productSelectRow.itaxrate=product.itaxrate;
        this.productSelectRow.saleprice=product.saleprice;
        this.productSelectRow.num=product.num;
        this.productSelectRow.rate=product.rate;
        this.productSelectRow.ordernum=product.ordernum;
        this.productSelectRow.price=parseFloat(product.saleprice*product.rate/100).toFixed(2);
      }
      this.productDialogVisible = false;
    }
  }
};
</script>

<style scoped>
.order-action-row {
  display: flex;
  align-items: center;
  justify-content: center;
}
.order-btn {
  min-width: 28px;
  height: 28px;
  padding: 0;
  margin: 0 2px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.order-input {
  width: 48px;
  height: 28px;
  margin: 0 2px;
  text-align: center;
}
.custom-controls {
  display: flex;
  align-items: center;
}
</style>
